package com.baitiaojun.moments.timer;

import com.alibaba.fastjson.JSONObject;
import com.baitiaojun.api.domain.user.RabbitMqDuplicate;
import com.baitiaojun.api.domain.moments.UserMoments;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.moments.handler.RabbitMqHandler;
import com.baitiaojun.moments.handler.UserMomentsCallBackHandler;
import com.baitiaojun.moments.service.DuplicateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @类名 TaskTimer
 * @描述 TODO 首次执行发布消息为false，后面为true
 * @作者 白条君
 * @创建日期 2022/11/28 20:04
 * @版本 1.0
 */
@Slf4j
@Component
public class PublishMqAckTimer {

    @Resource
    private RabbitMqHandler rabbitMqhandler;

    @Resource
    private UserMomentsCallBackHandler callBackHandler;

    @Resource
    private DuplicateService mqDuplicateService;

    @Scheduled(fixedDelay = 10000, initialDelay = 3000)
    public void process() throws Exception {
        log.info("定时器执行重新发送消息");
        List<RabbitMqDuplicate> mqDuplicateList = mqDuplicateService.getRabbitMqUserDuplicateListByStatus(ConstantUtil.DEFAULT_STATUS);
        if (ObjectUtils.isNotEmpty(mqDuplicateList) && mqDuplicateList.size() > 0) {
            List<Long> ids = new ArrayList<>();
            Iterator<RabbitMqDuplicate> iterator = mqDuplicateList.iterator();
            RabbitMqDuplicate mqDuplicate;
            while (iterator.hasNext()) {
                mqDuplicate = iterator.next();
                Long id = mqDuplicate.getId();
                int count = 0;
                for (; count < 2; count++) {
                    rabbitMqhandler.publishMoments(JSONObject.parseObject(mqDuplicate.getContent(), UserMoments.class), id);
                    if (callBackHandler.isAck()) {
                        iterator.remove();
                        break;
                    }
                }
                if (count == 2) {
                    //作为ids传递
                    ids.add(id);
                }
            }
            if (!mqDuplicateList.isEmpty()) {
                mqDuplicateService.batchUpdateMqUserDuplicateByIds(ids, ConstantUtil.FAIL_STATUS);
            }
        }
    }
}